package com.tianya.forum.services.impl;

import com.tianya.forum.common.AppResult;
import com.tianya.forum.common.ResultCode;
import com.tianya.forum.dao.UserMapper;
import com.tianya.forum.exception.ApplicationException;
import com.tianya.forum.model.User;
import com.tianya.forum.services.IUserService;
import com.tianya.forum.utils.MD5Utils;
import com.tianya.forum.utils.StringUtil;
import com.tianya.forum.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Date;


@Slf4j
@Service
public class UserServiceImpl implements IUserService {
    @Resource
    private UserMapper userMapper;

    /**
     * 注册用户
     * @param user
     */
    @Override
    public void createNormalUser(User user) {
        if(user == null){
            log.warn(ResultCode.ERROR_IS_NULL.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //查询当前用户是否存在
        User existuser = userMapper.selectByUserName(user.getUsername());
        if(existuser != null){
            log.warn(ResultCode.AILED_USER_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.AILED_USER_EXISTS));
        }
        // 除了注册时传⼊的有效值，其他全部使⽤默认
        if (user.getGender() == null) {
            // 性别赋默认值
            user.setGender((byte) 2);
        }
        // 填充默认值
        user.setIsAdmin((byte) 0);
        user.setAvatarUrl(null);
        user.setArticleCount(0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);
        // 插入数据库
        int row = userMapper.insertSelective(user);
        if(row != 1){
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //新增成功
        log.info("新增⽤⼾成功：username = " + user.getUsername());

    }

    @Override
    public User selectByUserName(String username) {
        return userMapper.selectByUserName(username);
    }


    /**
     * 登录功能
     * @param username
     * @param password
     * @return
     */
    @Override
    public User login(String username, String password) {
        User user = userMapper.selectByUserName(username);
        if(user == null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(ResultCode.FAILED_USER_NOT_EXISTS.toString());
        }
        //校验密码是否正确
        String salt = user.getSalt();
        String miwen = MD5Utils.md5Salt(password, salt);
        if(!user.getPassword().equalsIgnoreCase(miwen)){
            log.warn(ResultCode.FAILED_LOGIN.toString());
            throw new ApplicationException(ResultCode.FAILED_LOGIN.toString());
        }
        return user;
    }

    /**
     * 根据id查询用户
     * @param id
     * @return
     */
    @Override
    public User selectById(Long id) {
        if(id == null){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        return userMapper.selectByPrimaryKey(id);
    }

    /**
     * 根据用户id使用户帖子数量加一
     * @param id
     */
    @Override
    public void addArticleCountById(Long id) {
        //参数校验
        if(id == null){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        //根据用户id查询用户
        User user = userMapper.selectByPrimaryKey(id);
        int count = user.getArticleCount();
        //创建新用户对象用于更新
        User newuer = new User();
        newuer.setId(user.getId());
        newuer.setArticleCount(count+1);
        int row = userMapper.updateByPrimaryKeySelective(newuer);
        if(row != 1){
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }


    /**
     * ⽤⼾发帖数 -1
     * @param id 版块Id
     */
    @Override
    public void subOneArticleCountById(Long id) {
        //参数校验
        if(id == null || id <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        //根据用户id查询用户
        User user = userMapper.selectByPrimaryKey(id);
        //创建新用户对象用于更新
        User newuer = new User();
        newuer.setId(user.getId());
        newuer.setArticleCount(user.getArticleCount()-1);
        int row = userMapper.updateByPrimaryKeySelective(newuer);
        if(row != 1){
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyInfo(User user) {
        // 1. ⾮空校验
        if(user == null || user.getId() == null || user.getId() <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        // 2. 校验⽤⼾是否存在
        User existsUser = userMapper.selectByPrimaryKey(user.getId());
        if(existsUser == null){
            // 打印⽇志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //3. 定义⼀个标志位
        boolean checkAttr = false; // false表⽰没有校验通过
        // 4. 定义⼀个专⻔⽤来更新的对象，防⽌⽤⼾传⼊的User对象设置了其他的属性
        // 当使⽤动态SQL进⾏更新的时候，覆盖了没有经过校验的字段
        User updateUser = new User();
        // 5. 设置⽤⼾Id
        updateUser.setId(user.getId());
        // 6. 对每个⼀个参数进⾏校验并赋值
        if(!StringUtil.isEmpty(user.getUsername())
                && !existsUser.getUsername().equals(user.getUsername())){
            User checkUser = userMapper.selectByUserName(user.getUsername());
            if(checkUser != null){
                // ⽤⼾已存在
                log.warn(ResultCode.AILED_USER_EXISTS.toString());
                // 抛出异常
                throw new ApplicationException(AppResult.failed(ResultCode.AILED_USER_EXISTS));
            }
            // 数据库中没有找到相应的⽤⼾，表⽰可以修改⽤⼾名
            updateUser.setUsername(user.getUsername());
            // 更新标志位
            checkAttr = true;
        }
        // 7. 校验昵称
        if(!StringUtil.isEmpty(user.getNickname()) && !user.getNickname().equals(existsUser.getNickname())){
            // 设置昵称
            updateUser.setNickname(user.getNickname());
            // 更新标志位
            checkAttr = true;
        }
        // 8. 校验性别
        if (user.getGender() != null && user.getGender() !=
                existsUser.getGender()) {
            // 设置性别
            updateUser.setGender(user.getGender());
            // 合法性校验
            if (updateUser.getGender() > 2 || updateUser.getGender() < 0) {
                updateUser.setGender((byte) 2);
            }
            // 更新标志位
            checkAttr = true;
        }
        // 9. 校验邮箱
        if (!StringUtil.isEmpty(user.getEmail())
                && !user.getEmail().equals(existsUser.getEmail())) {
            // 设置邮箱
            updateUser.setEmail(user.getEmail());
            // 更新标志位
            checkAttr = true;
        }
        // 9. 校验电话号码
        if (!StringUtil.isEmpty(user.getPhoneNum())
                && !user.getPhoneNum().equals(existsUser.getPhoneNum())) {
            // 设置电话号码
            updateUser.setPhoneNum(user.getPhoneNum());
            // 更新标志位
            checkAttr = true;
        }// 10. 校验个⼈简介
        if (!StringUtil.isEmpty(user.getRemark())
                && !user.getRemark().equals(existsUser.getRemark())) {
            // 设置电话号码
            updateUser.setRemark(user.getRemark());
            // 更新标志位
            checkAttr = true;
        }
        // 11. 根据标志位来决定是否可以执⾏更新
        if(!checkAttr) {
            // 打印⽇志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 12. 调⽤DAO
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row != 1){
            log.warn(ResultCode.FAILED.toString() + ", 受影响的⾏数不等于 1 .");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }


    /**
     * 修改⽤⼾密码
     * @param id ⽤⼾Id
     * @param newPassword 新密码
     * @param oldPassword ⽼密码
     */
    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
        User user = userMapper.selectByPrimaryKey(id);
        if(user == null){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        String panduan = MD5Utils.md5Salt(oldPassword,user.getSalt());
        //校验原密码是否正确
        if(!user.getPassword().equalsIgnoreCase(panduan)){
            // 记录⽇志
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString() + "username = "
                    + user.getUsername() + ", password = " + oldPassword);
            // 密码不正确抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        String salt = UUIDUtil.UUID_32();
        String encryptPassword = MD5Utils.md5Salt(newPassword,salt);
        //创建⽤于更新的User对象
        User updateUser = new User();
        updateUser.setId(id);
        updateUser.setPassword(encryptPassword);
        updateUser.setSalt(salt);
        // 设置更新时间
        updateUser.setUpdateTime(new Date());
        int row = userMapper.updateByPrimaryKeySelective(updateUser);if(row != 1){
            log.warn(ResultCode.FAILED.toString() + ", 受影响的⾏数不等于 1 .");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }
}
